/**
 * @ Author 何涛
 * @ Date 2016/02/19 01:08:39
 */

//检查对象是否为数组   cc.isArray
tyNamespace.isArray = function (obj) {
	return obj instanceof Array;
};

tyNamespace.checkStore = function (obj) {
	return !(obj == null || obj.length == 0);
};

//检查对象是否为正数
tyNamespace.isPositiveNumber = function (obj) {
	var reg = /^\d+(?=\.{0,1}\d+$|$)/;
	return !!reg.test(obj);

};

//随机数
tyNamespace.randomNumber = function (min, max) {
	return Math.floor(Math.random() * (max - min + 1) + min);
};

//位数补零
tyNamespace.FullZero = function (value, len) {
	while (value.length < len) {
		value = "0" + value;
	}
	return value;
};

//格式 天：时：分：秒
tyNamespace.FormatSeconds = function (time) {
	var s = parseInt(time);
	var m = 0;
	var h = 0;
	var d = 0;
	if (s > 60) {
		m = parseInt(s / 60);
		s = parseInt(s % 60);
		if (m > 60) {
			h = parseInt(m / 60);
			m = parseInt(m % 60);
			if (h > 24) {
				d = parseInt(h / 24);
				h = parseInt(h % 24);
			}
		}
	}
	if (parseInt(time) > 60 * 60 * 24) {
		//cc.log("d,h,m,s:" + d + "|" + h + "|" + m + "|" + s);
		//cc.log("天，小时：" + tyNamespace.FullZero(d.toString(), 2) + tyNamespace.FullZero(h.toString(), 2));
		return tyNamespace.FullZero(d.toString(), 2) + ":" + tyNamespace.FullZero(h.toString(), 2);
	}
	if (parseInt(time) > 60 * 60 && parseInt(time) <= 60 * 60 * 24) {
		//cc.log("d,h,m,s:" + d + "|" + h + "|" + m + "|" + s);
		//cc.log("小时,分钟：" + tyNamespace.FullZero(h.toString(), 2) + tyNamespace.FullZero(m.toString(), 2));
		return tyNamespace.FullZero(h.toString(), 2) + ":" + tyNamespace.FullZero(m.toString(), 2);
	}
	if (parseInt(time) > 60 && parseInt(time) <= 60 * 60) {
		//cc.log("d,h,m,s:" + d + "|" + h + "|" + m + "|" + s);
		//cc.log("分钟,秒：" + tyNamespace.FullZero(m.toString(), 2) + tyNamespace.FullZero(s.toString(), 2));
		return tyNamespace.FullZero(m.toString(), 2) + ":" + tyNamespace.FullZero(s.toString(), 2);
	}
	else {
		//cc.log("d,h,m,s:" + d + "|" + h + "|" + m + "|" + s);
		//cc.log("分钟,秒：" + tyNamespace.FullZero(m.toString(), 2) + tyNamespace.FullZero(s.toString(), 2));
		return tyNamespace.FullZero(m.toString(), 2) + ":" + tyNamespace.FullZero(s.toString(), 2);
	}
	//return tyNamespace.FullZero(m, 10).toString() + ":" + tyNamespace.FullZero(s, 10).toString();
};

tyNamespace.GetRealLength = function (str) {
	var length = 0;
	for (var i = 0; i < str.length; i++) {
		var c = str.charCodeAt(i);
		if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
			length++;
		}
		else {
			length += 2;
		}
	}
	return length;
};

tyNamespace.GetStringArray = function (str) {
	var lengthArray = [];
	for (var i = 0; i < str.length; i++) {
		var c = str.charCodeAt(i);
		if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
			lengthArray.push(false);
		}
		else {
			lengthArray.push(true);
		}
	}
	return lengthArray;
};

tyNamespace.SlicedString = [];
tyNamespace.GetSlicedString = function (str, realSingleLength) {
	var realLength = tyNamespace.GetRealLength(str);
	var realArray = tyNamespace.GetStringArray(str);

	if (realLength > 0) {
		if (realLength < realSingleLength) {
			tyNamespace.SlicedString.push(str);
		}
		else {
			var length = 0, rLength = 0;
			for (var a = 0; a < realArray.length; a++) {
				length++;
				if (realArray[a])
					rLength += 2;
				else
					rLength++;
				if (rLength > realSingleLength)
					break;
			}
			tyNamespace.SlicedString.push(str.slice(0, length - 1));
			tyNamespace.GetSlicedString(str.slice(length - 1), realSingleLength);
		}

		return tyNamespace.SlicedString;
	}
};

/**
 * 字符串中插入某一个字符    例如：100,000,000
 * oldStr表示原字符串变量，insertStr表示要插入的字符串，index表示每隔几位插入
 */
 tyNamespace.InsertCharIntoString = function insert_flg(oldStr, insertStr, index) {
	var rightStr = "";
	var leftStr = oldStr.substr(0, oldStr.length % index);

	for (var i = oldStr.length - 1; i > oldStr.length % index; i -= index) {
		var tmp = oldStr.substring(i + 1 - index, i + 1).concat(rightStr);
		rightStr = insertStr.concat(tmp);
	}

	var newStr = leftStr.concat(rightStr);
	if (newStr.substr(0, 1) == ",")
		newStr = newStr.substring(1);

	return newStr;
 };

////检查对象是否为数组
//tyNamespace.isArray = function (obj) {
//return toString.apply(obj) === '[object Array]';
//};

////检查用户名    邮箱格式 最多20位
//tyNamespace.checkAccount = function (str) {
//return str.match(/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/);
//};

////检查用户密码   以字母开头，长度在6-20之间，只能包含大小写字母、数字和下划线。
//tyNamespace.checkAccount = function (str) {
//return str.match(/^\w{6,20}$/);
//};

////检查用户密码   以字母开头，长度在6-18之间，只能包含大小写字母、数字和下划线。
//tyNamespace.checkPassword = function (str) {
//return str.match(/^\w{6,18}$/);
//};

////检查用户邮箱   邮箱格式 最多20位
//tyNamespace.checkMail = function (str) {
//return str.match(/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/);
//};

 tyNamespace.setMenuEnable = function (sender) {
	 sender.getParent().setEnabled(false);
	 sender.scheduleOnce(function () {
		 sender.getParent().setEnabled(true);
	 }, 0.5);
 };

//生成按钮按下的效果sprite
 tyNamespace.maskSprite = cc.Sprite.extend({
	 ctor: function (fileName, rect, rotated) {
		 this._super(fileName, rect, rotated);

		 this.mask();

		 return true;
	 },

	 mask: function () {
		 var itemColor = this.getColor();
		 this.setColor(cc.color(itemColor.r * 0.5, itemColor.g * 0.5, itemColor.b * 0.5, itemColor.a * 0.5));
	 }
 });

 tyNamespace.loadImg = function (goodID, position, target) {
	 //正式服
	 var url = "http://otstatic.daofenggame.com/sfqq/upLoad/goods/" + goodID + ".png";

	 ////测试服
	 //var url = "http://219.83.160.99:80/mrsk/getUrl?id=" + goodID;

	 cc.log(url);

	 cc.loader.loadImg(url, {width: 100, height: 100}, function (err, texture) {
		 if (err)
			 cc.log(err);
		 else {
			 try {
				 if (!(texture instanceof cc.Texture2D)) {
					 var texture2d = new cc.Texture2D();
					 texture2d.initWithElement(texture);
					 texture2d.handleLoadedTexture();
					 texture = texture2d;
				 }

				 var sprite = new cc.Sprite();
				 sprite.initWithTexture(texture);
				 sprite.setPosition(position);
				 target.addChild(sprite);

			 } catch (e) {
				 cc.log("e.name：" + e.name + "-" + "e.message：" + e.message);
				 //tyNamespace.addTextRemoveLayer("e.name：" + e.name + "-" + "e.message：" + e.message);
			 }
		 }

		 tyNamespace.removeWaitLayer();
	 });
 };

 tyNamespace.loadImgByUrl = function (url, callback, target, arg) {
	 cc.log("tyNamespace.loadImgByUrl:" + url);

	 if (url.length == 0) {
		 if (arg == undefined)
			 callback.call(target);
		 else
			 callback.call(target, arg);
		 return;
	 }

	 cc.loader.loadImg(url, {width: 100, height: 100}, function (err, texture) {
		 if (err) {
			 cc.log("e:" + err);
			 callback.call(target, null, arg);
		 } else {
			 try {
				 if (!(texture instanceof cc.Texture2D)) {
					 var texture2d = new cc.Texture2D();
					 texture2d.initWithElement(texture);
					 texture2d.handleLoadedTexture();
					 texture = texture2d;
				 }
				 if (arg == undefined)
					 callback.call(target, texture);
				 else
					 callback.call(target, texture, arg);
			 } catch (e) {
				 cc.log("e.name：" + e.name + "-" + "e.message：" + e.message);
			 }
		 }
	 });
 };

 var LoadHead = cc.Sprite.extend({
	 headUrl: "",
	 m_Width: 0,
	 m_Height: 0,
	 m_headID: 0,
	 ctor: function (headID) {
		 if (headID <= 0)
			 headID = 1;

		 this.m_headID = headID;
		 this._super();

		 if (headID <= 800) {
			 var str = tyNamespace.FullZero(headID.toString(), 3);
			 var imageName = "zjm_qqtx_" + str + "u.png";

			 cc.log(imageName);

			 var spriteFrame = cc.spriteFrameCache.getSpriteFrame(imageName);
			 this.initWithSpriteFrame(spriteFrame);
		 }
	 },
	 onExit: function () {
		 this._super();
		 this.setHeadTexture = null;
	 },
	 loadImg: function () {
		 if (this.m_headID < 801)
			 return;

		 var self = this;

		 if (self.loadComplete) {
			 self.loadComplete();
		 }
	 },

	 loadGood: function (goodIconID, zhao) {
		 if (goodIconID != null && goodIconID >= 5000 && goodIconID < 5062) {
			 var goodIconName = "sc_swjp_" + this.getIconName(goodIconID, 4999) + "u.png";

			 var spriteFrame = cc.spriteFrameCache.getSpriteFrame(goodIconName);
			 this.initWithSpriteFrame(spriteFrame);

			 this.removeZhao(zhao);
		 }

		 //正式服
		 var url = "http://otstatic.daofenggame.com/sfqq/upLoad/goods/" + this.m_headID + ".png";

		 var that = this;

		 cc.log(url);

		 cc.loader.loadImg(url, {width: 100, height: 100}, function (err, texture) {
			 if (err) {
				 cc.log(err);
				 that.removeZhao(zhao);
			 } else {
				 try {
					 if (!(texture instanceof cc.Texture2D)) {
						 var texture2d = new cc.Texture2D();
						 texture2d.initWithElement(texture);
						 texture2d.handleLoadedTexture();
						 texture = texture2d;
					 }
					 that.setHeadTexture(texture);
				 }
				 catch (e) {
					 cc.log("e.name" + e.name + "-" + "e.message" + e.message + "-" + "e.message" + e.description);
				 }

				 that.removeZhao(zhao);
			 }
		 });
	 },

	 getIconName: function (iconID, offset) {
		 var realName = (iconID - offset).toString();
		 while (realName.length < 3) {
			 realName = "0" + realName;
		 }
		 return realName;
	 },

	 loadComplete: function () {
		 //加载远程图片
		 var self = this;
		 var url = this.headUrl;
		 if (!URL_HEAD_LIST[url]) {
			 URL_HEAD_LIST[url] = [];
			 URL_HEAD_LIST[url].push(this);
			 ht.log("xygame", "load head remote...");
			 cc.loader.loadImg(url, {width: 100, height: 100}, function (err, texture) {
				 ht.log("xygame", "load head remote get.");
				 if (err) {
					 return ht.log("xygame", "load head error " + err);
				 }
				 if (texture instanceof cc.Texture2D == false) {
					 URL_HEAD_LIST[url] = null;
					 return;
				 }
				 /*if(self.setTexture){
                 xy.NativeExpand.debugLog("xygame", "set head "+self);
                 self.setTexture(texture);
                 }*/
				 var list = URL_HEAD_LIST[url];
				 for (var i = 0; i < list.length; i++) {
					 var cur = list[i];
					 if (cur.setHeadTexture) {
						 cur.setHeadTexture(texture);
					 }
				 }
				 cc.textureCache.removeTexture(texture);
				 URL_HEAD_LIST[url] = null;
				 ht.log("xygame", "load head remote done.");
			 });
		 } else {
			 ht.log("xygame", "load head push " + this);
			 URL_HEAD_LIST[url].push(this);
		 }
	 },

	 setHeadTexture: function (texture) {
		 if (texture) {
			 ht.log("xygame", "set head " + this);
			 this.initWithTexture(texture);
			 if (this.m_Width > 0 && this.m_Height > 0) {
				 this.setHeadWH(this.m_Width, this.m_Height);
			 }
		 }
	 },

	 setHeadData: function (headID, _w, _h) {
		 _w = _w || 0;
		 _h = _h || 0;
		 if (this.m_headID == headID) return;
		 ht.log("xygame", "set head data headID:" + headID + " width:" + _w + " height:" + _h);
		 this.m_headID = headID;
		 this.loadImg(headID);
		 this.setHeadWH(_w, _h);
	 },

	 setHeadWH: function (_w, _h) {
//		 ht.log("xygame", "set scale width:"+_w+" height:"+_h);
		 var _size = this.getContentSize();
		 this.m_Width = _w;
		 this.m_Height = _h;
		 if (_size && _size.width > 0 && _size.height > 0) {
			 var xsW = this.m_Width / _size.width;
			 var xsH = this.m_Height / _size.height;
			 if (xsW > 0 && xsH > 0) {
//				 ht.log("xygame", "set scale "+xsW+":"+xsH);
				 this.setScale(xsW, xsH);
			 }
		 }

		 this.anchorX = 0;
		 this.anchorY = 0;
	 },

	 getheadID: function () {
		 return this.m_headID;
	 }
 });

//提示弹窗
 tyNamespace.tipsJumper = function (btType,WarningSectencesIndex,callback) {
	 var runningScene = cc.director.getRunningScene();
	 var modelLayerCancelable = new tyNamespace.ModelLayerCancelable();
	 var modelLayer = new tyNamespace.ModelLayer(70);
	 modelLayer.setTouchArea(cc.size(695, 500), cc.p(288, 125));
	 modelLayerCancelable.addChild(modelLayer);
	 runningScene.addChild(modelLayerCancelable, 10);
	 var jumpLayer = new tyNamespace.TipsLayer(btType,WarningSectencesIndex,callback);
	 jumpLayer.attr({
		 //左上角坐标
		 x: 0,
		 y: cc.winSize.height,
	 });
	 modelLayer.addChild(jumpLayer);
	 tyNamespace.AnimationManager.nodeJumpShow(jumpLayer, -cc.winSize.height);
 };

//警告弹窗
 tyNamespace.warningJumper = function (btType,WarningSectencesIndex) {
	 var runningScene = cc.director.getRunningScene();
	 var modelLayerCancelable = new tyNamespace.ModelLayerCancelable();
	 var modelLayer = new tyNamespace.ModelLayer(70);
	 modelLayer.setTouchArea(cc.size(695, 500), cc.p(288, 125));
	 modelLayerCancelable.addChild(modelLayer);
	 runningScene.addChild(modelLayerCancelable, 10);
	 var jumpLayer = new tyNamespace.WarningLayer(btType,WarningSectencesIndex);
	 jumpLayer.attr({
		 //左上角坐标
		 x: 0,
		 y: cc.winSize.height,
	 });
	 modelLayer.addChild(jumpLayer);
	 tyNamespace.AnimationManager.nodeJumpShow(jumpLayer, -cc.winSize.height);
 };

 tyNamespace.duangDuangFirst = function(node,callback){
	 node.runAction(cc.sequence(cc.scaleTo(0.1, 1.04, 0.96), cc.scaleTo(0.1, 0.96, 1.04), cc.scaleTo(0.1, 1, 1), cc.callFunc(callback, node)));      
 };

tyNamespace.fadeInThenOut = function(string){
	var stringTTF = new cc.LabelTTF(string, gpNamespace.DEFAULTFONT, 25);
	stringTTF.setFontFillColor(cc.color.WHITE,128);
	stringTTF.attr({
		x:cc.winSize.width/2,
		y:100
	});
	stringTTF.setOpacity(0);
	var runningScene = cc.director.getRunningScene();
	runningScene.addChild(stringTTF,10);
	stringTTF.runAction(new cc.FadeTo(0.5,255));
	runningScene.scheduleOnce(function(){
		stringTTF.runAction(new cc.FadeOut(1));
	},1);
};

 tyNamespace.checkMoney = function(limitGold){
	 var currentGold = userInfo.gold;
	 var pochanCount = gpNamespace.LoginInfo.POCHANCOUNT;
	 if (!tyNamespace.checkStore(pochanCount))
		 pochanCount = 0;
	 if (parseInt(currentGold) < 100 && parseInt(pochanCount) < 3) {
		 tyNamespace.IsPochan = true;
		 gpNamespace.GameConfig.SCENETYPE = 0;
		 cc.director.runScene(new cc.TransitionFade(0.5, new gpNamespace.GpMainScene()));
		 return false;
	 }
	 var oneRMB = gpNamespace.LoginInfo.ISBUYONE;
	 cc.log("pochanCount:" + pochanCount);
	 if (parseInt(currentGold) < 100 && parseInt(pochanCount) >= 3 && !oneRMB) {
		 tyNamespace.IsBuyOne = true;
		 gpNamespace.GameConfig.SCENETYPE = 0;
		 cc.director.runScene(new cc.TransitionFade(0.5, new gpNamespace.GpMainScene()));
		 return false;
	 }
	 if (!tyNamespace.IsPochan && !gpNamespace.IsBuyOne && parseInt(currentGold) < parseInt(limitGold)) {
		 tyNamespace.IsLimit = true;
		 gpNamespace.GameConfig.SCENETYPE = 0;
		 cc.director.runScene(new cc.TransitionFade(0.5, new gpNamespace.GpMainScene()));
				 return false;
			 }
		 return true;
 };

 
 gpNamespace.showDialog = function(msg) {
	 cc.log("gpNamespace.showDialog msg：" + msg);
 };